package com.base.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Paths;

@Controller
public class HtmlCotroller {

    private Logger logger = LoggerFactory.getLogger(HtmlCotroller.class);


    @GetMapping("/html/{path}/{page}")
    public String html(@PathVariable("path") String path, @PathVariable("page") String page) {
        return path + "/" + page;
    }

    @GetMapping("/html/cdr/{path}/{page}")
    public String htmlcdr(@PathVariable("path") String path, @PathVariable("page") String page) {
        return "cdr/" + path + "/" + page;
    }

    @GetMapping("/")
    public String html() {

        return "page/index";
    }

    @GetMapping(value = "/login")
    public String login() {
        //iSysMenuService.login();
        return "page/login";
    }

    @GetMapping(value = "/download/{fileName:.+}")
    public ResponseEntity<?> download(@PathVariable String fileName, HttpServletRequest request) {
        // Load file as Resource
        String path = Paths.get("D:/Insurance/", fileName).toString();
        Resource resource = new DefaultResourceLoader().getResource("file:" + path);

        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

}
